#!/usr/bin/env python
# coding: utf-8

# In[4]:


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, recall_score, f1_score, roc_auc_score, confusion_matrix, roc_curve
import matplotlib.pyplot as plt
import seaborn as sns

# 设置 Matplotlib 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定中文字体为黑体
plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号

# 加载数据
data = pd.read_excel('C:/Users/Administrator/Desktop/股票客户流失.xlsx')

# 数据清洗
data.dropna(inplace=True)  # 删除缺失值

# 特征缩放
scaler = StandardScaler()
data[['账户资金（元）', '最后一次交易距今时间（天）', '上月交易佣金（元）', '累计交易佣金（元）', '本券商使用时长（年）']] = scaler.fit_transform(data[['账户资金（元）', '最后一次交易距今时间（天）', '上月交易佣金（元）', '累计交易佣金（元）', '本券商使用时长（年）']])

# 分割数据集
X = data.drop('是否流失', axis=1)
y = data['是否流失']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

# 模型预测
y_pred = model.predict(X_test)

# 模型评价
accuracy = accuracy_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_pred)

print(f'准确率：{accuracy}')
print(f'召回率：{recall}')
print(f'F1分数：{f1}')
print(f'AUC值：{roc_auc}')

# 绘制混淆矩阵
conf_matrix = confusion_matrix(y_test, y_pred)
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues')
plt.xlabel('预测值')
plt.ylabel('真实值')
plt.title('混淆矩阵')
plt.savefig(r'C:\Users\Administrator\Desktop\confusion_matrix.png')  # 保存到桌面
plt.show()

# 绘制ROC曲线
y_pred_proba = model.predict_proba(X_test)[:, 1]
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
plt.plot(fpr, tpr, label=f'AUC={roc_auc:.2f}')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC曲线')
plt.legend()
plt.savefig(r'C:\Users\Administrator\Desktop\roc_curve.png')  # 保存到桌面
plt.show()


# In[ ]:




